const initialState = {
  artileData: {} as ArticleMap,
  detail: {} as DetailData,
};

type ArticleMap = {
  [key: number]: ArticleData;
};

export type ActionType =
  | { type: 'article/saveArticle'; payload: { channel_id: number; data: ArticleData } }
  | { type: 'article/refresh'; payload: { channel_id: number; data: ArticleData } }
  | { type: 'article/saveDetail'; payload: DetailData };

export default function articleReducer(
  state = initialState,
  action: ActionType
): typeof initialState {
  switch (action.type) {
    case 'article/saveArticle':
      const oldList = (state.artileData[action.payload.channel_id] || {}).results || [];
      const newList = [...oldList, ...action.payload.data.results];
      return {
        ...state,
        artileData: {
          ...state.artileData,
          [action.payload.channel_id]: {
            ...action.payload.data,
            results: newList,
          },
        },
      };

    case 'article/refresh':
      return {
        ...state,
        artileData: {
          ...state.artileData,
          [action.payload.channel_id]: action.payload.data,
        },
      };
    case 'article/saveDetail':
      return {
        ...state,
        detail: action.payload,
      };

    default:
      return state;
  }
}

interface ArticleData {
  results: ArticleResult[];
  pre_timestamp: string;
}

export interface ArticleResult {
  art_id: string;
  title: string;
  aut_id: string;
  comm_count: number;
  pubdate: string;
  aut_name: string;
  is_top: number;
  cover: Cover;
}

interface Cover {
  type: number;
  images?: string[];
}

export interface DetailData {
  art_id: string;
  title: string;
  pubdate: string;
  aut_id: string;
  content: string;
  aut_name: string;
  aut_photo: string;
  is_followed: boolean;
  is_collected: boolean;
  attitude: number;
  comm_count: number;
  read_count: number;
  like_count: number;
}
